//
//  WKVideoHttpTool.m
//  WKDemo
//
//  Created by apple on 14-8-2.
//  Copyright (c) 2014年 com.app. All rights reserved.
//

#import "WKVideoHttpTool.h"
#import "WKVideoParam.h"
#import "WKVideoResult.h"
#import "WKVidelModel.h"
#import "MJExtension.h"
#import "WKCommentResult.h"
#import "WKVideoModelFrame.h"
#import "FMDB.h"

@implementation WKVideoHttpTool
/** 数据库实例 */
static FMDatabase *_db;

+ (void)initialize
{
    // 1.获得数据库文件的路径
    NSString *doc = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    NSString *filename = [doc stringByAppendingPathComponent:@"videos.sqlite"];
    // 2.得到数据库
    _db = [FMDatabase databaseWithPath:filename];
    
    // 3.打开数据库
    if ([_db open]) {
        // 4.创表
        BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_video_videos (id integer PRIMARY KEY AUTOINCREMENT, maxid text NOT NULL,video_id text NOT NULL, video_dict blob NOT NULL);"];
        if (result) {
//           WKLog(@"成功创表");
        } else {
            NSLog(@"创表失败");
        }
    }
}
/**
 *  通过请求参数去数据库中加载对应的微博数据
 *
 *  @param param 请求参数
 */
+ (NSArray *)cachedHomeStatuses
{
    // 创建数组缓存微博数据
    NSMutableArray *statuses = [NSMutableArray array];
    
    // 根据请求参数查询数据
    FMResultSet *resultSet = nil;
   
        //resultSet = [_db executeQuery:@"SELECT * FROM t_video_videos ORDER BY video_id ASC ;"];
   resultSet = [_db executeQuery:@"SELECT * FROM t_video_videos;"];
    
    // 遍历查询结果
    while (resultSet.next) {
        NSData *statusDictData = [resultSet objectForColumnName:@"video_dict"];
        NSDictionary *statusDict = [NSKeyedUnarchiver unarchiveObjectWithData:statusDictData];
        
        // 字典转模型
        WKVidelModel *status = [WKVidelModel objectWithKeyValues:statusDict];
        // 添加模型到数组中
        [statuses addObject:status];
    }
    WKLog(@"在数据库中读取");
    return statuses;
}

/**
 *  缓存微博字典数组到数据库中
 */
+ (void)saveHomeStatusDictArray:(NSArray *)statusDictArray andMaxid:(NSString *)maxid
{
    for (NSDictionary *statusDict in statusDictArray) {
        // 把statusDict字典对象序列化成NSData二进制数据
        NSData *data = [NSKeyedArchiver archivedDataWithRootObject:statusDict];
        [_db executeUpdate:@"INSERT INTO t_video_videos ( maxid,video_id, video_dict) VALUES (?,?, ?);",maxid,
          statusDict[@"id"], data];
    }
}

//精华的请求
//获取主页默认列表也是下拉获取最新数据
+ (void)getBestNewDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *))success failure:(void (^)(NSError *error))failure
{
//    NSArray *datas = [self cachedHomeStatuses];
//   
//    WKLog(@"%d",datas.count);
//    if (datas.count!= 0) {
//        if (success) {
//            NSMutableArray *arrayM = [NSMutableArray array];
//            [datas enumerateObjectsUsingBlock:^(WKVidelModel *obj, NSUInteger idx, BOOL *stop) {
//                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
//                frame.videoModel = obj;
//                [arrayM addObject:frame];
//            }];
//            WKVideoResult *result =[[WKVideoResult alloc] init];
//            result.homeDatas = arrayM;
//            success(result);
//        }
//    }else
//    {
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:@"http://api.budejie.com/api/api_open.php?market=baidu&udid=860642023466269&a=list&c=video&userID=&page=1&per=20&visiting=&maxtime=" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//        
//        NSArray *array = responseObject[@"list"];
//        [self saveHomeStatusDictArray:array andMaxid:responseObject[@"info"][@"maxid"]];
        if (success) {
//            NSString *count = responseObject[@"info"][@"count"];
            
            NSString *maxid = responseObject[@"info"][@"maxtime"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
               frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    }
//}
+ (void)getBestDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *))success failure:(void (^)(NSError *error))failure
{        AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
        [mgr GET:@"http://api.budejie.com/api/api_open.php?market=baidu&udid=860642023466269&a=list&c=video&userID=&page=1&per=20&visiting=&maxtime=" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
//            
//            NSArray *array = responseObject[@"list"];
//            [self saveHomeStatusDictArray:array andMaxid:responseObject[@"info"][@"maxid"]];
            if (success) {
//                NSString *count = responseObject[@"info"][@"count"];
                
                NSString *maxid = responseObject[@"info"][@"maxtime"];
                NSMutableArray *arrayM = [NSMutableArray array];
                [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                    WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                    WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                    frame.videoModel = r;
                    [arrayM addObject:frame];
                }];
                
                WKVideoResult *result =[[WKVideoResult alloc] init];
                result.homeDatas = arrayM;
                result.maxtime = maxid;
                
                success(result);
            }
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            if (failure) {
                failure(error);
            }
        }];
    }


//上拉加载数据
//int k = 1;
+ (void)getBestMoreDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *result))success failure:(void (^)(NSError *error))failure{


    NSString *maxid =[NSString stringWithFormat:@"%@",param.maxtime];
//    k++;
    
    NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?market=baidu&udid=860642023466269&a=list&c=video&userID=&page=1&per=20&visiting=&maxtime=%@",maxid];

    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
                if (success) {
            
            NSString *maxid = responseObject[@"info"][@"maxtime"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
}
//获取评论
+ (void)getCommentDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *))success failure:(void (^)(NSError *error))failure{
    NSString *dataid = param.id;
    NSString *path = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?&market=baidu&udid=860642023466269&c=comment&a=dataList&data_id=%@&userID&per=20&page=1&hot=1",dataid];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"data"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKCommentResult *r = [WKCommentResult objectWithKeyValues:obj];
                r.username = obj[@"user"][@"username"];
                r.sex = obj[@"user"][@"sex"];
                r.profile_image = obj[@"user"][@"profile_image"];
                [arrayM addObject:r];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            
            success(result);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}
+ (void)getForwardNewDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *result))success failure:(void (^)(NSError *error))failure{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:@"http://api.budejie.com/api/api_open.php?market=baidu&udid=860642023466269&a=newlist&c=video&userID=&page=1&per=20&visiting=&maxtime=" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            //            NSString *count = responseObject[@"info"][@"count"];
            
            NSString *maxid = responseObject[@"info"][@"maxtime"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}

//最新的请求
//获取主页默认列表也是下拉获取最新数据
+ (void)getForwardDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *result))success failure:(void (^)(NSError *error))failure{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:@"http://api.budejie.com/api/api_open.php?order=timewarp&market=baidu&udid=860642023466269&a=list&c=video&userID=&page=1&per=20&visiting=&maxtime=" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
//            NSString *count = responseObject[@"info"][@"count"];
            
            NSString *maxid = responseObject[@"info"][@"maxtime"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}
//int l = 1;
//上拉加载数据
+ (void)getForwardMoreDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *result))success failure:(void (^)(NSError *error))failure{
    
    //NSString *maxid =[NSString stringWithFormat:@"%@",param.maxtime];
  // l++;
    
    NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?market=baidu&udid=860642023466269&a=list&c=video&userID=&page=1&per=20&visiting=&ver=3.9.3&maxtime=%@",param.maxtime];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            WKLog(@"%@",responseObject);
            NSString *maxid = responseObject[@"info"][@"maxtime"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}


//穿越的请求
//获取主页默认列表也是下拉获取最新数据
+ (void)getCrossNewDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *result))success failure:(void (^)(NSError *error))failure{
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:@"http://api.budejie.com/api/api_open.php?order=timewarp&market=baidu&maxid=&udid=860642023466269&a=list&c=video&userID=&page=1&per=20&visiting=&type=41&time=week" parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
//            NSString *count = responseObject[@"info"][@"count"];
            
            NSString *maxid = responseObject[@"info"][@"maxid"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}
//int m = 1;
//上拉加载数据
+ (void)getCrossMoreDataListWithParam:(WKVideoParam *)param success:(void (^)(WKVideoResult *result))success failure:(void (^)(NSError *error))failure{
    NSString *maxid =param.maxtime;
    //m++;
    
    NSString *url = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?order=timewarp&market=baidu&udid=860642023466269&a=list&c=video&os=4.0.3&userID=&page=1&per=20&visiting=&maxtime=%@",maxid];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:url parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        if (success) {
            
            NSString *maxid = responseObject[@"info"][@"maxtime"];
            NSMutableArray *arrayM = [NSMutableArray array];
            [responseObject[@"list"] enumerateObjectsUsingBlock:^(NSDictionary *obj, NSUInteger idx, BOOL *stop) {
                WKVidelModel *r = [WKVidelModel objectWithKeyValues:obj];
                
                WKVideoModelFrame *frame = [[WKVideoModelFrame alloc] init];
                frame.videoModel = r;
                [arrayM addObject:frame];
            }];
            WKVideoResult *result =[[WKVideoResult alloc] init];
            result.homeDatas = arrayM;
            result.maxtime = maxid;
            
            success(result);
            
        }
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        if (failure) {
            failure(error);
        }
    }];
    
}


//点赞
+ (void)sendClickLoveWithParam:(WKVideoParam *)param{
    NSString *di =param.id;
    NSString *path = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?&market=baidu&udid=860642023466269&c=video&a=love&dong=love&id=%@",di];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
//点菜
+ (void)sendClickCaiWithParam:(WKVideoParam *)param{
    NSString *di =param.id;
    NSString *path = [NSString stringWithFormat:@"http://api.budejie.com/api/api_open.php?&market=baidu&udid=860642023466269&c=video&a=cai&dong=love&id=%@",di];
    AFHTTPRequestOperationManager *mgr = [AFHTTPRequestOperationManager manager];
    [mgr GET:path parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
    
}

@end
